function initSwitch() {
    let tabSession = document.querySelector('.tab_session');
    console.dir(tabSession);
    let tabFriend = document.querySelector('.tab_friend');
    let lists = document.querySelectorAll('.list');
    tabSession.onclick = function() {
        tabSession.style.backgroundImage = 'url(./images/对话1.png)'
        tabFriend.style.backgroundImage = 'url(./images/朋友.png)'
        lists[0].classList = 'list'
        lists[1].classList = 'list hiden'
    }

    tabFriend.onclick = function() {
        tabSession.style.backgroundImage = 'url(./images/对话.png)'
        tabFriend.style.backgroundImage = 'url(./images/朋友1.png)'
        lists[0].classList = 'list hiden'
        lists[1].classList = 'list'
    }
}

initSwitch();

function getUserInfo() {
    $.ajax({
        method: 'get',
        url: '/user/getUserInfo',
        success: function(body) {
            if (body.data != null && body.status == 200) {
                let userDiv = document.querySelector('.client_container .main .left .user span');
                console.dir(userDiv);
                userDiv.innerHTML = body.data.userName;
                userDiv.setAttribute('userId',body.data.userId);
            }
        },
        error: function(body) {
            alert("您当前未登录，请登陆后再试吧！");
            location.href = 'login.html'
        }
    });
}

getUserInfo();

function getSessionList() {
    $.ajax({
        method: 'get',
        url: '/message/getSessionList',
        success: function(body) {
            if (body.data != null && body.status == 200) {
                let sessionListUL = document.querySelector('#session-list')
                sessionListUL.innerHTML = ''
                for (let session of body.data) {
                    if (session.lastTime.length > 10) {
                        session.lastTime = session.lastTime.subString(0,10) + '...';
                    }
                    let li = document.createElement('li');
                    li.setAttribute('message-session-id',session.sessionId);
                    li.innerHTML = '<h3>' + session.friends[0].friendName + '</h3>' 
                        + '<p>' + session.lastTime + '</p>';
                    sessionListUL.appendChild(li);
                    li.onclick = function() {
                        setHighLight(li);
                        getMessageInfos(session.sessionId,session.friends[0].friendName)
                    }
                }
            }
        },
    });
}

getSessionList();

function getMessageInfos(sessionId,friendName) {
    console.log('执行getMessageInfosBySessonId');
    $.ajax({
        method: 'get',
        url: '/messageInfo/getMessageInfosBySessionId?sessionId=' + sessionId,
        success: function(body) {
            let userDiv = document.querySelector('.client_container .main .left .user span');
            let userId = userDiv.getAttribute('userId');
            console.log(userId)
            let messageShow = document.querySelector('.client_container .main .right .message-show');
            messageShow.innerHTML = ''
            let titleDiv = document.querySelector('.client_container .main .right .title')
            titleDiv.innerHTML = friendName
            for (let message of body.data) {
                let messageDiv = document.createElement('div');
                messageDiv.classList.add('message')
                if (message.fromId == userId) {
                    messageDiv.classList.add('message-right');
                    messageDiv.innerHTML = '<div class="box">' + 
                    '<h4>' + userDiv.innerHTML + '</h4>' + '<p>' +
                    message.message + '</p>' + '</div>'
                }else {
                    messageDiv.classList.add('message-left')
                    messageDiv.innerHTML = '<div class="box">' + 
                    '<h4>' + friendName + '</h4>' + '<p>' +
                    message.message + '</p>' + '</div>'
                }
                messageShow.appendChild(messageDiv);
            }
            scrollBottom(messageShow);
        }
    });
}

function scrollBottom(elem) {
    let clientHeight = elem.offsetHeight;
    let scrollHeight = elem.scrollHeight;
    elem.scrollTo(0,scrollHeight - clientHeight);
}


function setHighLight(currentLi) {
    let lis = document.querySelectorAll('#session-list li');
    for (let li of lis) {
        if (li == currentLi) {
            li.className = 'selected';
        }else {
            li.className = '';
        }
    }
}

function getFriendList() {
    let friendList = document.querySelector('#friend-list');
    friendList.innerHTML = '';
    $.ajax({
        method: 'get',
        url: '/friend/getFriendList',
        success: function(body) {
            console.log(body);
            if (body != null && body.status == 200) {
                for (let friend of body.data) {
                    let li = document.createElement('li');
                    li.innerHTML = '<h4>' + friend.userName + '</h4>';
                    li.setAttribute('userId',friend.userId);
                    friendList.appendChild(li);
                    li.onclick = function() {
                        clickFriend(friend.userId,friend.userName);
                    }
                }
            }
        },
    });
}

getFriendList();

function clickFriend(friendId,friendName) {
    $.ajax({
        method: 'post',
        url: '/friend/isSessionExist',
        data: {
            friendId: friendId
        },
        success: function(body) {
            if (body.data != -1) {
                let sessionList = document.querySelector('#session-list');
                let lis = document.querySelectorAll('#session-list li');
                for (let currentLi of lis) {
                    console.dir(currentLi)
                    if (currentLi.getAttribute('message-session-id') == body.data) {
                        currentLi.click();
                        sessionList.insertBefore(currentLi,sessionList.children[0]);
                        console.log(currentLi)
                    }
                }
            }else {
                $.ajax({
                    method: 'post',
                    url: '/message/createSession',
                    data: {
                        friendId: friendId
                    },
                    success: function(body) {
                        let li = document.createElement('li');
                        li.setAttribute('message-session-id',body.data);
                        li.innerHTML = '<h3>' + friendName + '</h3>' 
                            + '<p></p>';
                        li.onclick = function() {
                            setHighLight(li);
                        }
                        let sessionList = document.querySelector('#session-list');
                        sessionList.insertBefore(li,sessionList.children[0])
                        li.click();
                    }
                });
            }
            let tabSession = document.querySelector('.tab .tab_session');
            tabSession.click();
        }   
    });
}

let websocket = new WebSocket('ws://127.0.0.1:8080/websocket');
websocket.onmessage = function(e) {
    console.log(e)
    let ret = JSON.parse(e.data)
    let li = document.querySelector('.left .selected p')
    if (ret.content.length > 10) {
        ret.content = ret.content.subString(0,10)
    }
    if (li == null) {
        let lis = document.querySelectorAll('.left #session-list li')
        for (let li of lis) {
            if (li.getAttribute('message-session-id') == ret.sessionId) {
                li.querySelector('p').innerHTML = ret.content
                break
            }
        }
    }else {
        let messageShow = document.querySelector('.client_container .main .right .message-show')
        let newDiv = document.createElement('div')
    newDiv.classList.add('message','message-left')
    newDiv.innerHTML = '<div class="box">' + '<h4>' + ret.fromName
        + '</h4>' + '<p>' + ret.content + '</p>' + '</div>'
    messageShow.appendChild(newDiv)
        li.innerHTML = ret.content
        scrollBottom(messageShow);
    }
}

let sendBtn = document.querySelector('.right .ctrl button');

sendBtn.onclick = function() {
    let inputText = document.querySelector('.right .message-input textarea');
    let session = document.querySelector('.left #session-list .selected')
    console.dir(session)
    let title = document.querySelector('.right .title')
    console.dir(title)
    let name = document.querySelector('.left .user span')
    let messageShow = document.querySelector('.client_container .main .right .message-show')
    let newDiv = document.createElement('div')
    newDiv.classList.add('message','message-right')
    newDiv.innerHTML = '<div class="box">' + '<h4>' + name.innerHTML
        + '</h4>' + '<p>' + inputText.value + '</p>' + '</div>'
    messageShow.appendChild(newDiv)
    let li = document.querySelector('.left .selected p')
    let sessionId = session.getAttribute('message-session-id')
    let req = {
        type: 'message',
        fromName: name.innerHTML,
        sessionId: sessionId,
        content: inputText.value
    }
    if (inputText.length > 10) {
        inputText.value = inputText.value.subString(0,10)
    }
    li.innerHTML = inputText.value
    inputText.value = ''
    scrollBottom(messageShow);
    websocket.send(JSON.stringify(req))
}